from fenrispunk_tools.config import (
    get_background_slug,
    get_grid,
    get_map_file,
    get_screen_size_default,
    get_sprite_length,
    get_tile_file,
)
from fenrispunk_tools.utils.grid_tile_key import get_tile
from fenrispunk_tools.utils.standard import get_datetime_stamp, get_max_dimensions


def generate_map_defaults(
    outfile=None,
    gridfile=None,
    tilesfile=None,
    screen_size=get_screen_size_default(),
    sprite_length=get_sprite_length(),
):
    # TODO: Validate the path and/or create parent directories.
    generate_map(
        outfile or f"var/fenrispunk_tools_screenshot_{get_datetime_stamp()}.jpeg",
        gridfile or get_map_file(),
        tilesfile or get_tile_file(),
        screen_size,
        sprite_length,
    )


def generate_map(outfile, gridfile, tilesfile, screen_size, sprite_length):
    # NOTE: Use this with the CLI tools. Import here so we keep the
    # stdout cleaner because pygame likes to talk.
    import pygame

    pygame.init()
    window = pygame.display.set_mode(screen_size)
    tiles = pygame.image.load(tilesfile)
    grid = get_grid(gridfile)
    screen = pygame.Surface(get_max_dimensions(grid, sprite_length))
    screen.fill(get_background_slug())
    for row in range(len(grid)):
        for col in range(len(grid[row])):
            screen.blit(
                source=tiles,
                dest=(col * sprite_length, row * sprite_length),
                area=get_tile(grid[row][col], sprite_length),
            )
    pygame.display.flip()
    pygame.image.save(
        screen,
        outfile,
    )
